import { Button } from 'antd';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';

const WebWorker = () => {
    console.log(123);
    const worker = useRef<any>(null);
    const [timeStr, setTimeStr] = useState('');
    const createWebWorker = () => {
        worker.current = new Worker(new URL('../../workers/index.worker.ts', import.meta.url));
        // 监听来自Worker的消息
        worker.current.onmessage = (e: MessageEvent<any>) => {
            console.log('eeeee', e.data);
            setTimeStr(e.data);
        };
        // 向Worker发送消息
        worker.current.postMessage(new Date().getTime());
    };
    const handleReOpen = () => {
        createWebWorker();
    };
    const handleClose = () => {
        worker.current.terminate();
        worker.current = null;
    };
    useEffect(() => {
        createWebWorker();
        return () => worker.current.terminate();
    }, []);
    return (
        <div className={styles['web-worker']}>
            <h2>{timeStr}</h2>
            <div className={styles.box}>
                <Button type="primary" onClick={handleReOpen}>
                    重新打开webwork
                </Button>
            </div>
            <div className={styles.box}>
                <Button type="default" onClick={handleClose}>
                    关闭webwork
                </Button>
            </div>
            <div className={styles.box}>
                <Button type="dashed" onClick={()=>{
                    // eslint-disable-next-line no-restricted-globals
                    confirm()
                    }}>
                    confirm
                </Button>
            </div>
        </div>
    );
};

export default WebWorker;
